<?php

namespace app\agent\model\wxapp;

use app\common\model\Wxapp as WxappModel;
use app\admin\model\store\User as StoreUser;
use app\admin\model\Setting as Setting;
use app\admin\model\WxappPage as WxappPage;
use app\admin\model\WxappCategory as WxappCategory;
use app\admin\model\WxappHelp as WxappHelp;
use think\Db;
use think\Session;

/**
 * 微信小程序模型
 * Class Wxapp
 * @package app\admin\model
 */
class Wxapp extends WxappModel{
    public function agent(){
        return $this->belongsTo('app\admin\model\agent\Agent');
    }
    /**
     * 获取小程序列表
     * @param boolean $is_recycle
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($is_recycle = false,$agentId=0){
        $session = Session::get('yoshop_agent');
        if($session['agent']['type']==0){
            $agent_id = $session['agent']['agent_id'];
            $info=Db::name('agent_user')->where(['pinpai_id'=>$session['agent']['pinpai_id'],'is_delete'=>0])->select();
            $resNext=$this->get_all_child($info->toArray(),$agent_id);
            $resNext[]=$session['agent']['agent_id'];
        }else{
            $info=Db::name('agent_user')->where(['recommend_id'=>$session['agent']['agent_id'],'is_delete'=>0])->select();
            $resNext=[];
            if($info){
                foreach ($info as $k=>$v){
                    $resNext[]=$v['agent_user_id'];
                }
            }
            $resNext[]=$session['agent']['agent_id'];
        }
        $r= Db::name('wxapp')
            ->alias('w')
            ->join('agent a','a.agent_id = w.agent_id')
            //->join('store_user u','u.wxapp_id = w.wxapp_id')
            //->where('u.is_super','=',1)
            ->where(['w.agent_id'=>['in',$resNext]])
            ->where('w.is_delete',0)
            ->order(['w.create_time' => 'desc'])
            ->field('a.*,w.*')
            ->paginate(15, false, [
                'query' => request()->request()
            ]);
        return $r;
    }
    /*
     * 获取字符串查询条件
     */
    private function getSelectStr($array,$field,$count){
        $str='';
        foreach($array as $k=>$v){
            if($k<$count-1){
                $str.=$v[$field].',';
            }else{
                $str.=$v[$field];
            }
        }
        return $str;
    }

    public function getwaterList($data){
        //获取当前登录人所有下级代理
        $session = Session::get('yoshop_agent');
        if($session['agent']['type']==0){
            $agent_id = $session['agent']['agent_id'];
            $info=Db::name('agent_user')->where(['pinpai_id'=>$session['agent']['pinpai_id']])->select();
            $resNext=$this->get_all_child($info->toArray(),$agent_id);
            $resNext[]=$session['agent']['agent_id'];
        }else{
            $info=Db::name('agent_user')->where(['recommend_id'=>$session['agent']['agent_id']])->select();
            $resNext=[];
            if($info){
                foreach ($info as $k=>$v){
                    $resNext[]=$v['agent_user_id'];
                }
            }
            $resNext[]=$session['agent']['agent_id'];
        }
        $storeList=Db::name('wxapp')->where(['agent_id'=>['in',$resNext],'active'=>1])->field('wxapp_id')->select();
        $countWxapp=count($storeList);
        $storeStr=$this->getSelectStr($storeList,'wxapp_id',$countWxapp);
        $map=[];
        //var_dump($data);
        if (isset($data['search']) && !empty($data['search'])) {
            $s=$data['search'];
            $map['p.shop_name']=['like','%'.trim($s).'%'];
        }
        if(!empty($data['start_time'])&&!empty($data['end_time'])){
            $map['o.create_time']=['between',[strtotime($data['start_time']),strtotime($data['end_time'])+86400]];
        }
        if(!empty($data['start_time'])&&empty($data['end_time'])){
            $map['o.create_time']=['>=',strtotime($data['start_time'])];
        }
        if(empty($data['start_time'])&&!empty($data['end_time'])){
            $map['o.create_time']=['<',strtotime($data['end_time'])+86400];
        }
        $map['o.wxapp_id']=['in',$storeStr];
        $todayStoreWater=Db::table('yoshop_order')
            ->alias('o')
            ->join('yoshop_store_shop p','o.wxapp_id = p.wxapp_id')
            ->join('yoshop_user u','o.user_id = u.user_id')
            ->where(['o.is_delete'=>0,'o.pay_status'=>20])
            //->where('o.wxapp_id','in' ,$storeStr)
            ->where($map)
            ->order('o.create_time','desc')
            //->whereTime('o.create_time', 'today')
            ->field('p.shop_name,p.address,o.order_source,o.total_price as amount,o.create_time,o.order_id,o.pay_type,o.user_id,u.nickName')
            ->paginate(15, false, [
                'query' => request()->request()
            ]);
        //var_dump($this->getLastSql());
        return $todayStoreWater;
    }
    //获取所有下级id  (不包含类型)
    private function get_all_child($array,$id){
        $arr = array();
        foreach($array as $v){
            if($v['recommend_id']==$id){
                $arr[] = $v['agent_user_id'];
                $arr = array_merge($arr,$this->get_all_child($array,$v['agent_user_id']));
            }
        };
        return $arr;
    }
    /*
     * 获取商户收入
     */
    public function getRevenueList($data){
        // 获取列表数据
        /* return $this->with(['wxapp'])
             ->alias('store')
             ->field("store.wxapp_id,FROM_UNIXTIME(store.create_time,'%Y-%m-%d') as dates,sum(amount) as amounts ,sum(payment) as payments")
             ->join('wxapp', 'wxapp.wxapp_id =store.wxapp_id')
             ->order(['dates' => 'desc','store.wxapp_id'=>'asc'])
             ->group("FROM_UNIXTIME(store.create_time,'%Y-%m-%d'),store.wxapp_id")
             ->paginate(15, false, [
                 'query' => request()->request()
             ]);*/
        //获取当前登录人所有下级代理
        $session = Session::get('yoshop_agent');
        if($session['agent']['type']==0){
            $agent_id = $session['agent']['agent_id'];
            $info=Db::name('agent_user')->where(['pinpai_id'=>$session['agent']['pinpai_id']])->select();
            $resNext=$this->get_all_child($info->toArray(),$agent_id);
            $resNext[]=$session['agent']['agent_id'];
        }else{
            $info=Db::name('agent_user')->where(['recommend_id'=>$session['agent']['agent_id']])->select();
            $resNext=[];
            if($info){
                foreach ($info as $k=>$v){
                    $resNext[]=$v['agent_user_id'];
                }
            }
            $resNext[]=$session['agent']['agent_id'];
        }
        $storeList=Db::name('wxapp')->where(['agent_id'=>['in',$resNext],'active'=>1])->field('wxapp_id')->select();
        $countWxapp=count($storeList);
        $storeStr=$this->getSelectStr($storeList,'wxapp_id',$countWxapp);
        $map=[];
        if (isset($data['search']) && !empty($data['search'])) {
            $s=$data['search'];
            $map['w.wxapp_name']=['like','%'.trim($s).'%'];
        }
        if(!empty($data['start_time'])&&!empty($data['end_time'])){
            $map['d.create_time']=['between',[strtotime($data['start_time']),strtotime($data['end_time'])+86400]];
        }
        if(!empty($data['start_time'])&&empty($data['end_time'])){
            $map['d.create_time']=['>=',strtotime($data['start_time'])];
        }
        if(empty($data['start_time'])&&!empty($data['end_time'])){
            $map['d.create_time']=['<',strtotime($data['end_time'])+86400];
        }
        $map['w.wxapp_id']=['in',$storeStr];
        $orderInfo=Db::table('yoshop_divide_store')
            ->alias('d')
            ->join('yoshop_wxapp w','w.wxapp_id = d.wxapp_id')
            ->where($map)
            ->order(['dates' => 'desc','d.wxapp_id'=>'asc'])
            ->group("FROM_UNIXTIME(d.create_time,'%Y-%m-%d'),d.wxapp_id")
            ->field("d.wxapp_id,FROM_UNIXTIME(d.create_time,'%Y-%m-%d') as dates,sum(amount) as amounts ,sum(payment) as payments,w.wxapp_name")
            ->paginate(15, false, [
                'query' => request()->request()
            ]);
        //var_dump($this->getLastSql());
        return $orderInfo;
    }
    /**
     * 获取提现列表
     */
    public function getOrderList($agentId,$page,$offset,$arr){
        $orderInfo=Db::table('yoshop_agent_cashout')
            ->alias('a')
            ->join('yoshop_agent_user u','a.agent_id = u.agent_user_id')
            ->where('u.agent_id','=' ,$agentId)
            ->where(['a.sh_status'=>$arr])
            ->field('a.*,u.real_name')
            ->limit($offset,$page)
            ->paginate(15,false,[
                'page'  =>$page
            ]);
        return $orderInfo;
    }
    /*
     * 获取当前代理商所有下级提现申请列表
     */
    public function getAgentOrderList($agentStr,$page,$offset){
        $orderInfo=Db::table('yoshop_agent_cashout')
            ->alias('a')
            ->join('yoshop_agent_user u','a.agent_id = u.agent_user_id')
            ->where('a.agent_id','in' ,$agentStr)
            ->field("a.id,a.money,a.pps_status,a.sh_status,a.pps_update_time,a.sh_update_time,a.agent_id,a.remark,a.isKaipiao,FROM_UNIXTIME(a.create_time,'%Y-%m-%d') as create_time,u.real_name,u.type")
            ->limit($offset,$page)
            ->paginate(15,false,[
                'page'  =>$page
            ]);
        return $orderInfo;
    }

    /**
     * 从缓存中获取商城名称
     * @param $data
     * @return array
     */
    public function getStoreName($data)
    {
        $names = [];
        foreach ($data as $wxapp) {
            $names[$wxapp['wxapp_id']] = Setting::getItem('store', $wxapp['wxapp_id'])['name'];
        }
        return $names;
    }

    /**type
     * 新增记录
     * @param $data
     * @return bool|mixed
     */
    public function add($data)
    {
        if ($data['password'] !== $data['password_confirm']) {
            $this->error = '确认密码不正确';
            return false;
        }
        if (StoreUser::checkExist($data['user_name'])) {
            $this->error = '商家用户名已存在';
            return false;
        }
        return $this->transaction(function () use ($data) {
            // 添加小程序记录
            $this->allowField(true)->save($data);
            // 商城默认设置
            (new Setting)->insertDefault($this['wxapp_id'], $data['store_name']);
            // 新增商家用户信息
            (new StoreUser)->add($this['wxapp_id'], $data);
            // 新增小程序默认帮助
            (new WxappHelp)->insertDefault($this['wxapp_id']);
            // 新增小程序diy配置
            (new WxappPage)->insertDefault($this['wxapp_id']);
            // 新增小程序分类页模板
            (new WxappCategory)->insertDefault($this['wxapp_id']);
            return $this->wxapp_id;
        });
    }

    /**
     * 移入移出回收站
     * @param bool $is_recycle
     * @return false|int
     */
    public function recycle($is_recycle = true)
    {
        return $this->save(['is_recycle' => (int)$is_recycle]);
    }

    /**
     * 软删除
     * @return false|int
     */
    public function setDelete()
    {
        return $this->transaction(function () {
            // 删除商家用户信息
            (new StoreUser)->setDelete($this['wxapp_id']);
            // 设置当前商城为已删除
            return $this->save(['is_delete' => 1]);
        });
    }

    /*
     * 获取商户基本信息
     */
    public function getWxappInfo($wxapp_id){
        $user=Db::name('wxapp')
            ->where('wxapp_id', '=', $wxapp_id)
            ->find();
        $in=Db::name('store_user')->where(['wxapp_id'=>$wxapp_id,'is_super'=>1,'is_delete'=>0])->find();
        $user['username']=$in['user_name'];
        return $user;
    }

}
